import Router from '@koa/router';
import logger from '../logger.js';
import response from '../response.js';
import { GetOpenID } from '../common/wx.js';
import  { generateOrderId,createOrder,refundOrder,queryRefundOrder,decryrsa} from '../common/fyPay.js';
import db from '../mysqlHelper.js';
import moment from 'moment';

const router = new Router();
router.prefix('/api');

router.post(`/applet/getOpenID`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.code == null) {
        ctx.body = response.fail('缺少必填字段 code');
        return;
    }
    let res = await GetOpenID(body.code);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    ctx.body = response.success(res.data, '获取OpenID成功');
});

router.post(`/fy/createOrder`, async (ctx) => {

    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.openid == null) {
        ctx.body = response.fail('缺少必填字段 openid');
        return;
    }
    if (body.order_id == null) {
        ctx.body = response.fail('缺少必填字段 order_id');
        return;
    }
    //检查订单是否存在
    let order=await db.findOne('order_info',{id:body.order_id});
    if(order==null){
        ctx.body = response.fail('订单号错误，请使用正确的订单号');
        return;
    }
    if(order.pay_status==10){
        ctx.body = response.fail('订单已支付，请勿重复支付');
        return;
    }
    let res = await createOrder(body.openid,  order.amount,order.work_level_name,order.work_level_name);
    if(res.code==0){
        ctx.body = response.fail(res.msg);
        return;
    }
    if(res.code==1){
        //更新订单状态
        order.order_date=res.order_date;
        order.pay_serial=res.data.order_id;
        try {
            await db.update('order_info',order,{id:body.order_id});
        } catch (error) {
            console.error('更新订单状态失败',error.message, JSON.stringify(order));
            ctx.body = response.fail('更新订单状态失败');
        }
    }
    ctx.body = response.success(res.data, '创建订单成功');
});

router.post(`/fy/refundOrder`, async (ctx) => {

    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.order_id == null) {
        ctx.body = response.fail('缺少必填字段 order_id');
        return;
    }
    let order=await db.findOne('order_info',{id:body.order_id});
    if(order==null){
        ctx.body = response.fail('订单号错误，请使用正确的订单号');
        return;
    }
    
    let res = await refundOrder(order.pay_serial,order.order_date,order.amount);
    if(res.code==0){
        ctx.body = response.fail(res.msg);
        return;
    }
    let refund_order={
        order_id:order.id,
        pay_serial:order.pay_serial,
        refund_time:moment().format('YYYY-MM-DD HH:mm:ss'),
        status:res.data.refund_st,
        refund_order_id:res.data.refund_order_id        
    }
    try {
        await db.create('refund_order',refund_order);
    } catch (error) {
        console.error('插入退款订单失败',error.message, JSON.stringify(refund_order));
        ctx.body = response.fail('插入退款订单失败');
    }
    ctx.body = response.success(res.data, '退款成功');
});

router.post(`/fy/queryRefundOrder`, async (ctx) => {

    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.order_id == null) {
        ctx.body = response.fail('缺少必填字段 order_id');
        return;
    }
    let refund=await db.findOne('refund_order',{order_id:body.order_id});
    if(refund==null){
        ctx.body = response.fail('订单号错误，请使用正确的订单号');
        return;
    }
    let refund_order_date=moment(refund.refund_time).format('YYYYMMDD');


    let res = await queryRefundOrder(refund_order_date,refund.refund_order_id);
    if(res.code==0){
        ctx.body = response.fail(res.msg);
        return;
    }
    refund.status=res.data.refund_st;
    try {
        await db.update('refund_order',{status:res.data.refund_st},{order_id:body.order_id});
    } catch (error) {
        console.error('更新退款状态失败',error.message, JSON.stringify(refund));
        ctx.body = response.fail('更新退款状态失败');
    }
    ctx.body = response.success(res.data, '查询退款状态成功');
});

//{"mchnt_cd":"0005810F7844011","order_date":"20241010","order_id":"17285475020128022006","order_amt":1,"order_pay_type":"LETPAY","back_notify_url":"http://39.104.15.44:88/api/fy/notify","goods_name":"网络工程师","goods_detail":"网络工程师","appid":"wxd1290d5442819e5b","openid":"olAiK7UZebp_bpNnrYfbl6Z6HwtY","ver":"1.0.0"}  
//解密message {"order_st":"1","pay_ssn":"4200002376202410107054289253","discount_info":"","pay_amt":"","order_pay_type":"LETPAY","openid":"olAiK7UZebp_bpNnrYfbl6Z6HwtY","card_type":"","sign_order_id":"","mchnt_cd":"0005810F7844011","pay_time":"20241010160533","order_date":"20241010","order_fas_date":"20241010","order_fas_ssn":"220336940740","fy_order_id":"500431653194","bill_params":"","order_amt":"1","order_id":"17285475020128022006"}
router.all(`/fy/notify`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    ctx.body = 'success';
    if(typeof(body)=='string'){
        console.info('富友支付回调为字符串',body);
        body=JSON.parse(body);
    }
    console.info('富友支付回调', JSON.stringify(body));
    let obj=decryrsa(body.message);
    if(obj==null){
        ctx.body = response.fail('解密失败');
        return;
    }
    console.info('富友支付回调',obj);
    try {
    obj=JSON.parse(obj);
    }
    catch (error) {
        console.error('解析失败',error.message, obj);
        return;
    }

    if(obj.order_st=='1'){
        //支付成功
        let order=await db.findOne('order_info',{pay_serial:obj.order_id});
        if(order==null){
            console.error('订单号错误，请使用正确的订单号', JSON.stringify(obj));
            return;
        }
        order.pay_status=10;
        order.pay_time=  moment(obj.pay_time,'YYYYMMDDHHmmss').format('YYYY-MM-DD HH:mm:ss');
        let res = await db.update('order_info',order,{id:order.id});
        if(res instanceof Error){
            console.error('更新订单状态失败',res.message, JSON.stringify(order));
           // ctx.body = response.fail('更新订单状态失败');
            return;
        }
        console.info('更新订单状态成功', JSON.stringify(order));
    }
});

export { router };
